package com.hgyc.mom.eam.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.context.FileServiceContext;
import com.hgyc.mom.common.enums.CommonOrderStatusEnum;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.eam.entity.*;
import com.hgyc.mom.eam.enums.EquipmentRepairStatusEnum;
import com.hgyc.mom.eam.enums.EquipmentUseStatusEnum;
import com.hgyc.mom.eam.mapper.EamEquipmentRepairMapper;
import com.hgyc.mom.eam.service.*;
import com.hgyc.mom.eam.vo.EamEquipmentRepairVO;
import com.hgyc.mom.tool.strategy.AutoCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备维修单Service业务层实现
 *
 * @author fwj
 * @since 2025-08-18
 */
@Slf4j
@Service
public class EamEquipmentRepairServiceImpl extends ServiceImpl<EamEquipmentRepairMapper, EamEquipmentRepair> implements EamEquipmentRepairService {

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private EamEquipmentService eamEquipmentService;

    @Autowired
    private EamEquipmentRepairAttachmentService eamEquipmentRepairAttachmentService;
    @Autowired
    private EamEquipmentRepairPartService eamEquipmentRepairPartService;
    @Autowired
    private EamEquipmentRepairReportService eamEquipmentRepairReportService;

    @Autowired
    private FileServiceContext fileServiceContext;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRepair(EamEquipmentRepair eamEquipmentRepair) {
        if (eamEquipmentRepair.getEquipmentId() == null) {
            throw new BizException("请选择维修设备!");
        }

        String code = autoCodeUtil.genSerialCode("equipment_repair_code", null);
        eamEquipmentRepair.setCode(code);
        eamEquipmentRepair.setRequestUser(StpUtil.getLoginIdAsLong());
        eamEquipmentRepair.setRequestTime(LocalDateTime.now());
        eamEquipmentRepair.setRepairStatus(EquipmentRepairStatusEnum.REQUEST.getValue());

        // 更新设备状态
        EamEquipment equipment = eamEquipmentService.getById(eamEquipmentRepair.getEquipmentId());
        equipment.setUseStatus(EquipmentUseStatusEnum.BREAKDOWN.getValue());
        eamEquipmentService.updateById(equipment);

        save(eamEquipmentRepair);
    }

    @Override
    public void updateRepair(EamEquipmentRepair eamEquipmentRepair) {
        // TODO 其他逻辑
        updateById(eamEquipmentRepair);
    }

    @Override
    public void removeRepair(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRecord(EamEquipmentRepairVO eamEquipmentRepairVO) {
        updateById(eamEquipmentRepairVO);

        if (eamEquipmentRepairVO.getRepairStatus() != null || EquipmentRepairStatusEnum.FINISH.getValue().equals(eamEquipmentRepairVO.getRepairStatus())) {
            eamEquipmentRepairVO.setRepairFinishTime(LocalDateTime.now());
            eamEquipmentRepairVO.setExecutor(StpUtil.getLoginIdAsLong());
        }

        //新增或更新设备维修报告
        EamEquipmentRepairReport report = eamEquipmentRepairVO.getRepairReport();
        if (report != null ) {
            if (report.getId() != null) {
                eamEquipmentRepairReportService.updateById(report);
            } else {
                report.setRepairId(eamEquipmentRepairVO.getId());
                eamEquipmentRepairReportService.save(report);
            }
        }

        //删除设备维修附件
        if (!CollectionUtils.isEmpty(eamEquipmentRepairVO.getDeleteAttachmentIds())) {
            for (Long id : eamEquipmentRepairVO.getDeleteAttachmentIds()) {
                EamEquipmentRepairAttachment attachment = eamEquipmentRepairAttachmentService.getById(id);
                if (attachment != null && attachment.getFileUrl() != null) {
                    fileServiceContext.deleteFile(attachment.getFileUrl());
                }
            }
            eamEquipmentRepairAttachmentService.removeBatchByIds(eamEquipmentRepairVO.getDeleteAttachmentIds());
        }

        //新增设备维修附件
        List<EamEquipmentRepairAttachment> attachments = eamEquipmentRepairVO.getAddAttachments();
        if (!CollectionUtils.isEmpty(attachments)) {
            attachments.forEach(item -> {
                item.setId(null);
                item.setRepairId(eamEquipmentRepairVO.getId());
            });
            eamEquipmentRepairAttachmentService.saveBatch(attachments);
        }

        //更新设备维修附件
        if (!CollectionUtils.isEmpty(eamEquipmentRepairVO.getUpdateAttachments())) {
            List<EamEquipmentRepairAttachment> updateAttachments = eamEquipmentRepairVO.getUpdateAttachments();
            eamEquipmentRepairAttachmentService.updateBatchById(updateAttachments);
        }
        //删除设备维修备件
        if (!CollectionUtils.isEmpty(eamEquipmentRepairVO.getDeletePartIds())) {
            eamEquipmentRepairPartService.removeBatchByIds(eamEquipmentRepairVO.getDeletePartIds());
        }

        //新增设备维修备件
        List<EamEquipmentRepairPart> parts = eamEquipmentRepairVO.getAddParts();
        if (!CollectionUtils.isEmpty(parts)) {
            parts.forEach(item -> {
                item.setId(null);
                item.setRepairId(eamEquipmentRepairVO.getId());
            });
            eamEquipmentRepairPartService.saveBatch(parts);
        }

        //更新设备维修备件
        if (!CollectionUtils.isEmpty(eamEquipmentRepairVO.getUpdateParts())) {
            List<EamEquipmentRepairPart> updateParts = eamEquipmentRepairVO.getUpdateParts();
            eamEquipmentRepairPartService.updateBatchById(updateParts);
        }
    }

    @Override
    public void startRepair(Long id) {
        LambdaUpdateWrapper<EamEquipmentRepair> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(EamEquipmentRepair::getId, id);
        updateWrapper.set(EamEquipmentRepair::getRepairStartTime, LocalDateTime.now());
        updateWrapper.set(EamEquipmentRepair::getRepairStatus, EquipmentRepairStatusEnum.IN_MAINTENANCE.getValue());
        update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<EamEquipmentRepair> eamEquipmentRepairList, boolean updateSupport) {
        if (eamEquipmentRepairList == null || eamEquipmentRepairList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + eamEquipmentRepairList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + eamEquipmentRepairList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("设备维修单导入失败", e);
            throw new BizException("设备维修单导入失败：" + e.getMessage());
        }
    }
}
